import axios from 'axios'
import { useUserStore } from '@/store/modules/user'
import { storeToRefs } from 'pinia'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // api 的 base_url
  timeout: 10 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    const { token } = storeToRefs(userStore)
    // Do something before request is sent
    if (token.value) {
      config.headers['Authorization'] = 'Bearer ' + token.value
    }
    return config
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use((response) => {
  const { success, message, data } = response.data
  if (success) {
    return data
  }
  // TODO: 统一处理错误
  return Promise.reject(new Error(message || 'Error'))
}, (error) => {
  // TODO: 统一处理错误
  if (error.response && error.response?.data && error.response?.data?.status === 401) {
    userStore.logout()
  }
  return Promise.reject(error)
})

export default service
